package com.li.action;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.li.hibernate.pojo.ShUser;
import com.li.service.UserService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class UserAction extends ActionSupport implements ModelDriven<ShUser> {

	private ShUser user = new ShUser();

	@Override
	public ShUser getModel() {
		// TODO Auto-generated method stub
		return user;
	}
	
	private String checkcode;
	
	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}
	
	private UserService userService;

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	
	public String registPage() {
		return "registPage";
	}

	
	public String findByName() throws IOException {
		
		ShUser existUser = userService.findByUsername(user.getUsername());
		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		
		if (existUser != null) {
			
			response.getWriter().println("<font color='red'>鐢ㄦ埛鍚嶅凡缁忓瓨鍦�/font>");
		} else {
			
			response.getWriter().println("<font color='green'>鐢ㄦ埛鍚嶅彲浠ヤ娇鐢�/font>");
		}
		return NONE;
	}

	
	public String regist() {
		
		String checkcode1 = (String) ServletActionContext.getRequest()
				.getSession().getAttribute("checkcode");
		if(!checkcode.equalsIgnoreCase(checkcode1)){
			this.addActionError("错误");
			return "checkcodeFail";
		}
		userService.save(user);
		this.addActionMessage("注册成功!");
		return "msg";
	}

	
	public String loginPage() {
		return "loginPage";
	}

	
	public String login() {
		ShUser existUser = userService.login(user);
	
		if (existUser == null) {
			
			this.addActionError("输入用户名和密码!");
			return LOGIN;
		} else {
			
			ServletActionContext.getRequest().getSession()
					.setAttribute("existUser", existUser);
			
			return "loginSuccess";
		}
	
	}


	
	
}
